package br.ufpb.di.knowledgetv.sqtv.utils;

import com.hp.hpl.jena.query.*;
import com.hp.hpl.jena.rdf.model.Model;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.FileReader;

public class SPARQLUtils {

    private static Logger logger = Logger.getLogger(SPARQLUtils.class);

	public static String readFileSparql(String file, String... replaces) {
		StringBuilder contents = new StringBuilder();
		String replaced = "";
		try {
			BufferedReader in = new BufferedReader(new FileReader(file));
			String text;
			while((text = in.readLine()) != null)
				contents.append(text);
			in.close();
			replaced = contents.toString();
			for (int i = 0; i < replaces.length; i++)
				replaced = replaced.replaceAll("\\{"+i+"\\}", replaces[i]);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return replaced;
	}
	
	public static ResultSet executeQuery(String endpoint, String sparql) {
        try {
            logger.debug("Executing SPARQL - " + sparql);
            Query query = QueryFactory.create(sparql);
            QueryExecution qe = QueryExecutionFactory.sparqlService(endpoint, query);
            ResultSet resultSet = qe.execSelect();
            return resultSet;
        } catch (Exception e){
            logger.error(e.getMessage(), e);
            return null;
        }
	}
	
	public static Model executeConstruct(String endpoint, String sparql) {
		Query query = QueryFactory.create(sparql);
		QueryExecution qe = QueryExecutionFactory.sparqlService(endpoint,query);
		Model resultModel = qe.execConstruct();
		return resultModel;
	}
	
	public static Model describeObject(String endpoint, String sparql) {
		Query query = QueryFactory.create(sparql);
		QueryExecution qe = QueryExecutionFactory.sparqlService(endpoint,query);
		Model resultModel = qe.execDescribe();
		return resultModel;
	}

	
}
